import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_rank.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'mine_integral_roules_page.dart';
import 'mine_my_score_integral_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///

enum IntegralRankType {
  person,
  depart,
}

///代码清单
class MineMyIntegralItemLevelPage extends StatefulWidget {
  final StreamController<String> dateSelectStream;

  MineMyIntegralItemLevelPage({Key key, this.dateSelectStream})
      : super(key: key);

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<MineMyIntegralItemLevelPage> {
  bool _isLoading = true;
  int _showCount = 1;

  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      {
        getMyIntegralStatDataFunction();
      }
    });

    if (widget.dateSelectStream != null) {
      _streamSubscription = widget.dateSelectStream.stream.listen((event) {
        _currentSelectDate = event;
        _isLoading = true;
        setState(() {});
        getMyIntegralStatDataFunction();
      });
    }
  }

  @override
  void dispose() {
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 600),
      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },

      ///执行动画的子 Widget
      ///只有子 Widget 被切换时才会触发动画
      child: buildMain(context),
    );
  }

  Widget buildMain(BuildContext context) {
    if (_isLoading) {
      return SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: Center(child: LoadingWidget()));
    }
    if (_rankStatBean == null) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyIntegralStatDataFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }

    return RefreshIndicator(
      key: ValueKey("$_showCount"),
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        ScrollMetrics scrollMetrics = notifation.metrics;
        if (scrollMetrics.minScrollExtent == 0) {
          return true;
        } else {
          return false;
        }
      },
      onRefresh: () async {
        await getMyIntegralStatDataFunction();
        ToastUtils.showToast("已刷新");
        return true;
      },
      child: NestedScrollView(
        body: ListView.builder(
          itemCount: _rankStatBean.firstStatistics.length,
          itemBuilder: (BuildContext context, int index) {
            RankUserStatBean rankUserStatBean;
            if (index < _rankStatBean.firstStatistics.length) {
              rankUserStatBean = _rankStatBean.firstStatistics[index];
            } else {
              rankUserStatBean = _rankStatBean
                  .lastStatistics[index - _rankStatBean.firstStatistics.length];
            }
            return Container(
              child: GestureDetector(
                  onTap: () {
                    if (_rankType == IntegralRankType.depart) {
                      ToastUtils.showToast("暂无详情");
                      return;
                    }
                    NavigatorUtils.pushPage(
                        context,
                        MyScoreIntegralRecoderPage(
                          userId: rankUserStatBean.userId,
                          startDate: _currentSelectDate,
                        ));
                  },
                  child: buildItemRankContainer(rankUserStatBean, index)),
            );
          },
        ),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              child: buildAvgScoreWidget(),
            ),
          ];
        },
      ),
    );
  }

  Container buildItemRankContainer(RankUserStatBean userStatBean, int index) {
    return Container(
      height: 66,
      margin: EdgeInsets.only(top: 10, left: 12, right: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              SizedBox(
                width: 12,
              ),
              Container(
                child: buildItemIndex(index),
                width: 40,
                alignment: Alignment.center,
              ),
              SizedBox(
                width: 12,
              ),
              Expanded(
                child: buildLeftColumn(userStatBean),
              ),
              SizedBox(
                width: 12,
              ),
              Container(
                alignment: Alignment.centerRight,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisSize: MainAxisSize.min,
                  children: [buildRightIntegralText(userStatBean)],
                ),
              ),
              SizedBox(
                width: 12,
              ),
            ],
          ),
          Container(
            height: 1.0,
            color: Colors.grey[200],
            margin: EdgeInsets.only(top: 8),
          ),
        ],
      ),
    );
  }

  Widget buildRightIntegralText(RankUserStatBean userStatBean) {
    String rankIntegralString = "${userStatBean.rankIntegralNumber.toInt()}分";
    if (_rankType == IntegralRankType.depart) {
      rankIntegralString = "均分 ${userStatBean.rankIntegralNumber}分";
      return Text(
        userStatBean == null ? "无" : "$rankIntegralString",
        style: TextStyle(
          color: Colors.black,
          fontSize: 14,
        ),
      );
    }
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          userStatBean == null ? "无" : "$rankIntegralString",
          style: TextStyle(
            color: Colors.black,
            fontSize: 14,
          ),
        ),
        Icon(
          Icons.arrow_forward_ios_sharp,
          size: 12,
        )
      ],
    );
  }

  Widget buildLeftColumn(RankUserStatBean userStatBean) {
    if (_rankType == IntegralRankType.depart) {
      return Container(
        height: 44,
        alignment: Alignment.centerLeft,
        child: Text(
          "${userStatBean.department}",
          style: TextStyle(
            color: Colors.black,
            fontSize: 16,
          ),
        ),
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          "${userStatBean.reamName}",
          style: TextStyle(
            color: Colors.blueGrey,
            fontSize: 16,
          ),
        ),
        SizedBox(
          height: 4,
        ),
        Text(
          "${userStatBean.department} - ${userStatBean.userPost}",
          style: TextStyle(
            color: Colors.grey,
            fontSize: 14,
          ),
        )
      ],
    );
  }

  Widget buildItemIndex(int index) {
    return index < 3
        ? Image.asset(
            "assets/images/2.0x/icon_rank_${index + 1}.png",
            width: 26,
          )
        : Text(
            "${index + 1}",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
          );
  }

  IntegralRankType _rankType = IntegralRankType.person;

  //平均分
  Widget buildAvgScoreWidget() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          margin: EdgeInsets.only(top: 16, bottom: 0),
          height: 200,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Container(
                  alignment: Alignment.center,
                  child: Image.asset(
                    buildRankImagePath(),
                    height: 200,
                  ),
                ),
              ),
              Positioned(
                top: 166,
                child: Text(
                  buildRankText(),
                  style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                      fontSize: 16),
                ),
              ),
              Positioned(
                left: 14,
                top: 0,
                child: Container(
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      InkWell(
                        onTap: () {
                          _rankType = IntegralRankType.person;
                          if (_rankPersonStatBean != null) {
                            _rankStatBean = _rankPersonStatBean;
                            ToastUtils.showToast("个人排名");
                            setState(() {
                              _showCount++;
                            });
                            return;
                          }
                          setState(() {
                            _isLoading = true;
                          });
                          getMyIntegralStatDataFunction();
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(
                              left: 8, right: 8, top: 4, bottom: 4),
                          child: Text(
                            "个人排名",
                            style: TextStyle(
                              color: _rankType == IntegralRankType.person
                                  ? Colors.white
                                  : Colors.red,
                            ),
                          ),
                          decoration: BoxDecoration(
                            color: _rankType == IntegralRankType.person
                                ? Colors.red
                                : Colors.white,
                            border: Border.all(color: Colors.red),
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(20),
                              bottomLeft: Radius.circular(20),
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          _rankType = IntegralRankType.depart;
                          if (_rankDepartStatBean != null) {
                            _rankStatBean = _rankDepartStatBean;
                            ToastUtils.showToast("部门排名");
                            setState(() {
                              _showCount++;
                            });
                            return;
                          }
                          getMyIntegralStatDataFunction();
                          setState(() {
                            _isLoading = true;
                          });
                        },
                        child: Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.only(
                              left: 8, right: 8, top: 4, bottom: 4),
                          child: Text(
                            "部门排名",
                            style: TextStyle(
                              color: _rankType == IntegralRankType.person
                                  ? Colors.red
                                  : Colors.white,
                            ),
                          ),
                          decoration: BoxDecoration(
                            color: _rankType == IntegralRankType.depart
                                ? Colors.red
                                : Colors.white,
                            border: Border.all(color: Colors.red),
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(20),
                              bottomRight: Radius.circular(20),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
        TextButton(
          onPressed: () {
            NavigatorUtils.pushPage(context, MineIntegralRoulesPage());
          },
          child: Text("查看积分规则"),
        ),
        buildUserRankContainer()
      ],
    );
  }

  Container buildUserRankContainer() {
    RankUserStatBean userStatBean = _rankStatBean.userStatistics;
    UserBean userBean = UserHelper.getInstance.userBean;
    return Container(
      height: 80,
      margin: EdgeInsets.only(top: 10, left: 12, right: 12),
      child: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              "assets/images/2.0x/bg_ranking_list_own.png",
              fit: BoxFit.fill,
            ),
          ),
          Positioned.fill(
            child: Row(
              children: [
                SizedBox(
                  width: 12,
                ),
                Icon(
                  Icons.scanner_outlined,
                  color: Colors.white,
                ),
                SizedBox(
                  width: 12,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        "${userBean.reamName}",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                        ),
                      ),
                      SizedBox(
                        height: 4,
                      ),
                      Text(
                        "${userBean.department} - ${userBean.userPost}",
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  width: 12,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      userStatBean == null
                          ? "无"
                          : "排名 第${userStatBean.rankNumber}名",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                      ),
                    ),
                    SizedBox(
                      height: 4,
                    ),
                    Text(
                      userStatBean == null
                          ? "无"
                          : "${userStatBean.rankIntegralNumber.toInt()}分",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    )
                  ],
                ),
                SizedBox(
                  width: 12,
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  String buildRankText() {
    RankUserStatBean userStatBean = _rankStatBean.userStatistics;
    if (userStatBean == null) {
      return "暂无排名";
    } else {
      String str = "第${userStatBean.rankNumber}名";
      return str;
    }
  }

  String buildRankImagePath() {
    RankUserStatBean userStatBean = _rankStatBean.userStatistics;
    if (userStatBean == null) {
      return "assets/images/2.0x/rank4.png";
    } else {
      String str = "assets/images/2.0x/rank${userStatBean.rankNumber}.png";
      if (userStatBean.rankNumber > 4) {
        str = "assets/images/2.0x/rank4.png";
      }
      return str;
    }
  }

  RankStatBean _rankStatBean;
  RankStatBean _rankPersonStatBean;
  RankStatBean _rankDepartStatBean;
  String _currentSelectDate =
      ViDateUtils.formatDate(DateTime.now(), format: "yyyy-MM");

  CancelToken _cancelToken;

  Future<bool> getMyIntegralStatDataFunction() async {
    Map<String, dynamic> monthMap = {
      "integralFlag": _rankType == IntegralRankType.person ? 0 : 1,
      "recoderType": -1,
      "sort": "TIMES",
      "date": "$_currentSelectDate-01 00:00:00"
    };
    if (_cancelToken != null && !_cancelToken.isCancelled) {
      _cancelToken.cancel();
    }
    _cancelToken = new CancelToken();
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.integralRankUrl,
      queryParameters: monthMap,
      cancelTag: _cancelToken,
    );

    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (responseData != null) {
        _rankStatBean = RankStatBean.fromJson(responseData);
        if (_rankType == IntegralRankType.person) {
          _rankPersonStatBean = _rankStatBean;
        } else {
          _rankDepartStatBean = _rankStatBean;
        }
      }
    }
    _isLoading = false;

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
